import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { 
  getCategoryTree,
  getCategoryList,
  getCategoryById,
  createCategory,
  updateCategory,
  deleteCategory,
  updateCategoryStatus,
  getParentCategories
} from '@/api/category'

// ==================== 异步操作 ====================

/**
 * 获取分类树
 */
export const fetchCategoryTree = createAsyncThunk(
  'category/fetchTree',
  async (_, { rejectWithValue }) => {
    try {
      const response = await getCategoryTree()
      return response.data || []
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

/**
 * 获取分类列表（分页）
 */
export const fetchCategoryList = createAsyncThunk(
  'category/fetchList',
  async (params, { rejectWithValue }) => {
    try {
      const response = await getCategoryList(params)
      // 将请求参数一起返回，用于更新分页状态
      return { ...response, requestParams: params }
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

/**
 * 获取分类详情
 */
export const fetchCategoryDetail = createAsyncThunk(
  'category/fetchDetail',
  async (id, { rejectWithValue }) => {
    try {
      const response = await getCategoryById(id)
      if (response.code === 200) {
        return response.data
      }
      return rejectWithValue(response.message || '获取分类详情失败')
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

/**
 * 新增分类
 */
export const addCategory = createAsyncThunk(
  'category/add',
  async (data, { rejectWithValue }) => {
    try {
      const response = await createCategory(data)
      if (response.code === 200) {
        return response.data
      }
      return rejectWithValue(response.message || '新增分类失败')
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

/**
 * 更新分类
 */
export const editCategory = createAsyncThunk(
  'category/edit',
  async ({ id, data }, { rejectWithValue }) => {
    try {
      const response = await updateCategory(id, data)
      if (response.code === 200) {
        return response.data
      }
      return rejectWithValue(response.message || '更新分类失败')
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

/**
 * 删除分类
 */
export const removeCategory = createAsyncThunk(
  'category/remove',
  async (id, { rejectWithValue }) => {
    try {
      const response = await deleteCategory(id)
      if (response.code === 200) {
        return id
      }
      return rejectWithValue(response.message || '删除分类失败')
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

/**
 * 更新分类状态
 */
export const changeCategoryStatus = createAsyncThunk(
  'category/changeStatus',
  async ({ id, isEnabled }, { rejectWithValue }) => {
    try {
      const response = await updateCategoryStatus(id, isEnabled)
      if (response.code === 200) {
        return { id, isEnabled }
      }
      return rejectWithValue(response.message || '更新状态失败')
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

/**
 * 获取父级分类列表
 */
export const fetchParentCategories = createAsyncThunk(
  'category/fetchParents',
  async (_, { rejectWithValue }) => {
    try {
      const response = await getParentCategories()
      return response.data || []
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

// ==================== Slice ====================

const categorySlice = createSlice({
  name: 'category',
  initialState: {
    // 分类树
    categoryTree: [],
    
    // 分类列表（分页）
    categoryList: [],
    total: 0,
    currentPage: 1,
    pageSize: 10,
    
    // 父级分类列表
    parentCategories: [],
    
    // 当前分类详情
    currentCategory: null,
    
    // 加载状态
    loading: false,
    treeLoading: false,
    detailLoading: false,
    
    // 错误信息
    error: null
  },
  reducers: {
    // 清空错误
    clearError: (state) => {
      state.error = null
    },
    // 重置当前分类
    resetCurrentCategory: (state) => {
      state.currentCategory = null
    },
    // 设置分页参数
    setPageParams: (state, action) => {
      state.currentPage = action.payload.page || state.currentPage
      state.pageSize = action.payload.size || state.pageSize
    }
  },
  extraReducers: (builder) => {
    builder
      // 获取分类树
      .addCase(fetchCategoryTree.pending, (state) => {
        state.treeLoading = true
        state.error = null
      })
      .addCase(fetchCategoryTree.fulfilled, (state, action) => {
        state.treeLoading = false
        state.categoryTree = action.payload || []
      })
      .addCase(fetchCategoryTree.rejected, (state, action) => {
        state.treeLoading = false
        state.error = action.payload || '获取分类树失败'
      })
      
      // 获取分类列表
      .addCase(fetchCategoryList.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchCategoryList.fulfilled, (state, action) => {
        state.loading = false
        state.categoryList = action.payload.data || []
        state.total = action.payload.total || 0
        // 使用请求参数更新分页状态（因为后端不返回分页字段）
        const params = action.payload.requestParams || {}
        if (params.page !== undefined) {
          state.currentPage = params.page
        }
        if (params.size !== undefined) {
          state.pageSize = params.size
        }
      })
      .addCase(fetchCategoryList.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload || '获取分类列表失败'
      })
      
      // 获取分类详情
      .addCase(fetchCategoryDetail.pending, (state) => {
        state.detailLoading = true
        state.error = null
      })
      .addCase(fetchCategoryDetail.fulfilled, (state, action) => {
        state.detailLoading = false
        state.currentCategory = action.payload
      })
      .addCase(fetchCategoryDetail.rejected, (state, action) => {
        state.detailLoading = false
        state.error = action.payload || '获取分类详情失败'
      })
      
      // 新增分类
      .addCase(addCategory.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(addCategory.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(addCategory.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload || '新增分类失败'
      })
      
      // 更新分类
      .addCase(editCategory.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(editCategory.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(editCategory.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload || '更新分类失败'
      })
      
      // 删除分类
      .addCase(removeCategory.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(removeCategory.fulfilled, (state, action) => {
        state.loading = false
        state.categoryList = state.categoryList.filter(cat => cat.id !== action.payload)
        state.total -= 1
      })
      .addCase(removeCategory.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload || '删除分类失败'
      })
      
      // 更新状态
      .addCase(changeCategoryStatus.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(changeCategoryStatus.fulfilled, (state, action) => {
        state.loading = false
        const category = state.categoryList.find(c => c.id === action.payload.id)
        if (category) {
          category.isEnabled = action.payload.isEnabled
        }
      })
      .addCase(changeCategoryStatus.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload || '更新状态失败'
      })
      
      // 获取父级分类
      .addCase(fetchParentCategories.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchParentCategories.fulfilled, (state, action) => {
        state.loading = false
        state.parentCategories = action.payload || []
      })
      .addCase(fetchParentCategories.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload || '获取父级分类失败'
      })
  }
})

export const { clearError, resetCurrentCategory, setPageParams } = categorySlice.actions

export default categorySlice.reducer

